package com.education.platform.api.service.impl;

import com.education.platform.api.config.ThreadUser;
import com.education.platform.api.service.AccountFlowService;
import com.education.platform.api.service.BuyService;
import com.education.platform.api.service.RelUserPaperService;
import com.education.platform.api.vo.request.BuyCourseVO;
import com.education.platform.common.enums.*;
import com.education.platform.common.exception.AssertException;
import com.education.platform.common.exception.BusinessException;
import com.education.platform.common.util.OrderNoGenerator;
import com.education.platform.common.web.ResponseCode;
import com.education.platform.dao.*;
import com.education.platform.dao.entity.*;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;

/**
 * 购买  课程   文章
 */
@Service
public class BuyServiceImpl implements BuyService {


    @Autowired
    private CourseDao courseDao;
    @Autowired
    private ArticleDao articleDao;
    @Autowired
    private AccountDao accountDao;
    @Autowired
    private AccountFlowService accountFlowService;
    @Autowired
    private UserOrderDao userOrderDao;
    @Autowired
    private RelUserPaperDao relUserPaperDao;
    @Autowired
    private RelUserPaperService relUserPaperService;
    /**
     * 购买文章/课程
     *
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean buyProduct(String orderType,Integer productId, Float totalPrice) {
        if(totalPrice==null ||totalPrice<=0){
            throw new BusinessException("价格不正确");
        }
        if (productId == null) {
            throw new BusinessException("购买对象id为空");
        }
        String coverImage =null;
        String   productName =null;
        Integer relType = null;
        FlowBusinessTypeEnum fbt;
        OrderTypeEnum orderTypeEnum;
       if(OrderTypeEnum.ARTICLE_ORDER.getValue().equals(orderType)){
           ArticleDO articleDO = articleDao.getById(productId);
           if(articleDO == null){
               throw new BusinessException("购买文章不存在");
           }
           coverImage = articleDO.getCover();
           productName = articleDO.getTitle();
           relType = RelTypeEnum.ARTICLE.getValue();
           orderTypeEnum = OrderTypeEnum.ARTICLE_ORDER;
           fbt = FlowBusinessTypeEnum.BUY_ARTICLE;
       }else if(OrderTypeEnum.COURSE_ORDER.getValue().equals(orderType)){
           CourseDO courseDO = courseDao.getById(productId);
           if(courseDO == null){
               throw new BusinessException("购买课程不存在");
           }
           coverImage = courseDO.getCourseImage();
           productName = courseDO.getCourseName();
           relType = RelTypeEnum.COURSE.getValue();
           fbt = FlowBusinessTypeEnum.BUY_COURSE;
           orderTypeEnum = OrderTypeEnum.COURSE_ORDER;
       }else {
           throw new BusinessException("不支持的操作");
        }
        //验证是否已经购买过
        relUserPaperService.checkRel(relType,productId);
       //检查账户豆子是否足够
        AccountDO account = this.checkBeans(totalPrice.intValue());
        String orderNo = this.saveOrder(totalPrice,coverImage,productId,productName,orderTypeEnum);
        this.saveRelUserProduct(productId,relType);
        this.increSalesNum(productId,orderType);
        //插入豆子流水记录
        accountFlowService.createAccountFlow(account, fbt, FlowTypeEnum.OUT, totalPrice.intValue(),orderNo);
        return true;
    }



    /**
     * 增加销量
     * @param productId
     * @param orderType
     */
    private void increSalesNum(Integer productId,String orderType){
        if(OrderTypeEnum.COURSE_ORDER.getValue().equals(orderType)){
            courseDao.incSalesNum(productId);
        }else if(OrderTypeEnum.ARTICLE_ORDER.getValue().equals(orderType)){
            articleDao.incSalesNum(productId);
        }
}



    /**
     * 检查账户豆子
     *
     * @param totalPrice
     */
    private AccountDO checkBeans(int totalPrice) {
        //检查历史豆是否足够
        AccountDO accountDO = accountDao.getByUserId(ThreadUser.getUserId());
        if (accountDO == null || accountDO.getBeanNumber() == null) {
            AssertException.throwBusinessEp("账户异常");
        }
        if (accountDO.getBeanNumber() < totalPrice) {
            throw new BusinessException("账户历史豆不足！", ResponseCode.NOT_ENOUGH.getCode());
        }
        AccountDO accountUpdate = new AccountDO();
        accountUpdate.setId(accountDO.getId());
        accountUpdate.setBeanNumber(accountDO.getBeanNumber() -totalPrice);
        accountUpdate.setUpdateTime(new Date());
        accountDao.updateById(accountUpdate);
        return accountDO;
    }

    /**
     * 保存关系
     * @param productId
     * @param relType
     */
    private void saveRelUserProduct( Integer productId,Integer relType){
        RelUserPaperDO relUserPaperDO = new RelUserPaperDO();
        relUserPaperDO.setUserId(ThreadUser.getUserId());
        relUserPaperDO.setPaperId(productId);
        relUserPaperDO.setCreateTime(new Date());
        relUserPaperDO.setDeleted(false);
        relUserPaperDO.setRelType(relType);
        relUserPaperDao.insert(relUserPaperDO);
    }

    /**
     * 保存订单
     * @param totalPrice
     * @param courseImage
     * @param productId
     * @param productName
     */
    private String saveOrder(Float totalPrice,String courseImage,Integer productId,String productName,OrderTypeEnum orderTypeEnum) {
        UserOrderDO userOrder = new UserOrderDO();
        userOrder.setUserId(ThreadUser.getUserId());
        userOrder.setUserName(ThreadUser.getUserName());
        userOrder.setOrderNo(OrderNoGenerator.generator());
        userOrder.setOrderStatus(OrderStatusEnum.COMPLETE.getValue());
        userOrder.setOrderStatusName(OrderStatusEnum.COMPLETE.getDes());
        userOrder.setCreateTime(new Date());
        userOrder.setOrderType(orderTypeEnum.getValue());
        userOrder.setOrderTypeName(orderTypeEnum.getDes());
        userOrder.setCoverImage(courseImage);
        userOrder.setGoodsId(productId);
        userOrder.setGoodsName(productName);
        userOrder.setTotalPrice(totalPrice.intValue());
        userOrder.setNumber(1);
        userOrder.setDeleted(false);
        userOrder.setPriceType(PriceTypeEnum.BEAN.getValue());
        userOrderDao.insert(userOrder);
        return userOrder.getOrderNo();
    }



}
